package com.mystudy.atomic.interger;

import java.util.HashSet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * TODO:
 *
 * @author acy
 * @since 2019/06/04 15:02
 */
public class AtomicIntegerTest {
	/**
	 * 1.可见性
	 * 2.内存屏障
	 * 3.不能保证原子性
	 */

	public static void main(String[] args) throws InterruptedException {
		final AtomicInteger value = new AtomicInteger();
		HashSet<Object> set = new HashSet<>();
		Thread thread = new Thread(() -> {
			int x = 0;
			while (x < 500) {
				//获取当前值然后自增
				int temp = value.getAndIncrement();
				set.add(temp);
				System.out.println(Thread.currentThread().getName() + ":" + temp);
				x++;
			}
		});
		Thread thread2 = new Thread(() -> {
			int x = 0;
			while (x < 500) {
				//获取当前值然后自增
				int temp = value.getAndIncrement();
				set.add(temp);
				System.out.println(Thread.currentThread().getName() + ":" + temp);
				x++;
			}
		});
		Thread thread3 = new Thread(() -> {
			int x = 0;
			while (x < 500) {
				//获取当前值然后自增
				int temp = value.getAndIncrement();
				set.add(temp);
				System.out.println(Thread.currentThread().getName() + ":" + temp);
				x++;
			}
		});
		thread.start();
		thread2.start();
		thread3.start();
		thread.join();
		thread2.join();
		thread3.join();
		System.out.println(set.size());
	}
}
